package com.xingkeduo.business.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xingkeduo.dto.*;
import com.xingkeduo.dto.param.*;
import com.xingkeduo.pojo.enums.CommentStar;
import com.xingkeduo.pojo.query.CommentsMapper;
import com.xingkeduo.pojo.query.LabelsMapper;
import com.xingkeduo.pojo.table.Comments;
import com.xingkeduo.pojo.table.Labels;
import com.xingkeduo.remote.AdminRemoteService;
import com.xingkeduo.remote.StoreRemoteService;
import com.xingkeduo.remote.WordPadRemoteService;
import com.xingkeduo.remote.feign.AdminFeignService;
import com.xingkeduo.remote.feign.OrderFeignService;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.utils.Constant;
import com.xingkeduo.utils.DateTimeUtils;
import com.xingkeduo.utils.PageResponseDTO;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

;

/**
 * @author chi  2019-02-21 19:35
 **/
@Service
@Slf4j
public class CommentsService {

    @Resource
    private CommentsMapper commentsMapper;

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private AdminRemoteService adminRemoteService;

    @Resource
    private LabelsMapper labelsMapper;

    @Resource
    private StoreRemoteService storeRemoteService;

    @Resource
    private WordPadRemoteService wordPadRemoteService;

    @Resource
    private AdminFeignService adminFeignService;


    public PageResponseDTO<CommentsResponseDto> selectListPage(CommentsQueryDto commentsQueryDto) {
        //构造查询参数
        LambdaQueryWrapper<Comments> queryWrapper = generateQuery(commentsQueryDto);
        IPage<Comments> orderIPage = commentsMapper.selectPage(commentsQueryDto.getPageObject(), queryWrapper);
        List<Comments> records = orderIPage.getRecords();
        if(records!=null && records.size()>0){
            Long[] ids = records.stream().map(Comments::getId).toArray(Long[]::new);
            LambdaQueryWrapper<Comments> queryWrappers = new QueryWrapper<Comments>().lambda().in(Comments::getId,ids).orderByDesc(Comments::getCreatedTime);;
            records= commentsMapper.selectList(queryWrappers);
        }


//        IPage<Comments> orderIPage = commentsMapper.selectPage(commentsQueryDto.getPageObject(), queryWrappers);

        List<CommentsResponseDto> collect = records.parallelStream()
                .map(this::covertToDto)
                .collect(Collectors.toList());
        PageResponseDTO<CommentsResponseDto> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }




    private LambdaQueryWrapper<Comments> generateQuery(CommentsQueryDto query) {

        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().select("id").lambda();

        if (StringUtils.isNotBlank(query.getVendorId())) {
            queryWrapper.eq(Comments::getVendorId, query.getVendorId());
        }

        if (StringUtils.isNotBlank(query.getCityId())) {
            queryWrapper.eq(Comments::getCityId, query.getCityId());
        }

        if (StringUtils.isNotBlank(query.getBranchOfficeId())) {
            queryWrapper.eq(Comments::getBranchOfficeId, query.getBranchOfficeId());
        }

        if (StringUtils.isNotBlank(query.getStoreId())) {
            queryWrapper.eq(Comments::getStoreId, query.getStoreId());
        }

        if (StringUtils.isNotBlank(query.getUserId())) {
            //代码优化 获取账号合并ids
            String[] strings = adminRemoteService.queryUserIds(query.getUserId());
            queryWrapper.in(Comments::getUserId, strings);
//            queryWrapper.eq(Comments::getUserId, query.getUserId());
        }

        if (query.getServiceType() != null) {
            queryWrapper.eq(Comments::getServiceType, query.getServiceType());
        }

        if (StringUtils.isNotBlank(query.getOrderNo())) {
            queryWrapper.eq(Comments::getOrderNo, query.getOrderNo());
        }

        if (StringUtils.isNotBlank(query.getAdminName())) {

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("condition", query.getAdminName());


            log.info("admin param:{}", jsonObject.toJSONString());
            ResponseUtils<String[]> responseUtils = null;
            try {
                responseUtils = adminFeignService.adminCondition(URLEncoder.encode(jsonObject.toJSONString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            log.info("admin response:{}", JSON.toJSONString(responseUtils));
            if (responseUtils.success()) {
                String[] data = responseUtils.getData();

                if (data != null && data.length > 0) {
                    queryWrapper.in(Comments::getAdminId, data);
                } else {
                    queryWrapper.eq(Comments::getId, 0L);
                }

            } else {
                queryWrapper.eq(Comments::getId, 0L);
            }
//            queryWrapper.like(Comments::getAdminName, query.getAdminName());
        }

        if (query.getServiceType() != null) {
            queryWrapper.eq(Comments::getServiceType, query.getServiceType());
        }

        if (query.getCommentStars() != null && query.getCommentStars().size()>0) {
            queryWrapper.in(Comments::getCommentStar, query.getCommentStars());
        }

        if (query.getIsEffective() != null) {
            queryWrapper.eq(Comments::getIsEffective, query.getIsEffective());
        }

        if (query.getAftermarketStatus() != null) {
            queryWrapper.eq(Comments::getAftermarketStatus, query.getAftermarketStatus());
        }

        if (StringUtils.isNotBlank(query.getServeStartTime()) || StringUtils.isNotBlank(query.getServeEndTime())) {
            String timeStart = query.getServeStartTime();
            String timeEnd = query.getServeEndTime();

            if(StringUtils.isBlank(timeStart)){
                timeStart = "1991-03-29 00:00";
            }
            if(StringUtils.isBlank(timeEnd)){
                timeEnd = "2100-01-01 00:00";
            }
            queryWrapper.between(Comments::getServeStartTime, DateTimeUtils.yyyy_MM_dd(timeStart), DateTimeUtils.yyyy_MM_dd(timeEnd));
        }

        if (StringUtils.isNotBlank(query.getUserInfo())) {
            queryWrapper.nested(i -> i
                    .like(Comments::getUserMobile, query.getUserInfo())
                    .or()
                    .like(Comments::getUserNickName, query.getUserInfo()));
        }

        queryWrapper.orderByDesc(Comments::getCreatedTime);

        return queryWrapper;
    }


    /**
     * 修改展示设置
     * @param commentsShownDto
     * @return
     */
    public boolean showConfig(CommentsShownDto commentsShownDto) {
        Comments comments = getCommentsById(commentsShownDto.getId());
        comments.setShownToAdmin(commentsShownDto.getShownToAdmin())
                .setShownToUser(commentsShownDto.getShownToUser());
        commentsMapper.updateById(comments);
        return true;
    }


    /**
     * 评论失效
     * @param commentsId
     * @return
     */
    public boolean invalid(String commentsId) {
        Comments comments = getCommentsById(commentsId).setIsEffective(false);
        commentsMapper.updateById(comments);
        return true;
    }


    public CommentsResponseDto covertToDto(Comments comments) {
        try {
            if(comments==null){
                return null;
            }
            supplementOrder(comments);
            CommentsResponseDto commentsResponseDto = new CommentsResponseDto();
            BeanUtils.copyProperties(comments, commentsResponseDto);
            commentsResponseDto.setPicIds( dispics(commentsResponseDto.getPicIds()));
            commentsResponseDto.covert();
            return commentsResponseDto;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        CommentsResponseDto commentsResponseDto = new CommentsResponseDto();
        BeanUtils.copyProperties(comments, commentsResponseDto);
        return commentsResponseDto;
    }

    public Comments getCommentsById(Serializable id) {
        Comments comments = commentsMapper.selectById(id);
        if (comments == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "订单不存在");
        }
        supplementOrder(comments);
        return comments;
    }

    public CommentsResponseDto queryById(String id) {
        Comments comments = getCommentsById(id);
        CommentsResponseDto commentsResponseDto = covertToDto(comments);
        return commentsResponseDto;
    }


    /**
     * 根据发型师id 查询发型师评论列表
     * @param queryByAdminIdDto
     * @return
     */
    public PageResponseDTO<QueryByAdminIdResponseDto> selectListAdminIdPage(QueryByAdminIdDto queryByAdminIdDto) {
        //构造查询参数
        LambdaQueryWrapper<Comments> queryWrapper = generateQueryByAdminId(queryByAdminIdDto);

        IPage<Comments> orderIPage = commentsMapper.selectPage(queryByAdminIdDto.getPageObject(), queryWrapper);

        List<QueryByAdminIdResponseDto> collect = orderIPage.getRecords().stream()
                .map(this::queryCovertToDto)
                .collect(Collectors.toList());
        PageResponseDTO<QueryByAdminIdResponseDto> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }

    /**
     * 处理返回数据
     * @param comments
     * @return
     */
    public QueryByAdminIdResponseDto queryCovertToDto(Comments comments) {
        if(comments==null){
            return null;
        }
        supplementOrder(comments);
        QueryByAdminIdResponseDto commentsResponseDto = new QueryByAdminIdResponseDto();
        BeanUtils.copyProperties(comments, commentsResponseDto);
        disposeNick(commentsResponseDto,comments);
        comments.setPicIds( dispics(comments.getPicIds()));
        commentsResponseDto.covert(comments);
        return commentsResponseDto;
    }


    /**
     * 发型师评价查询
     * @param query
     * @return
     */
    private LambdaQueryWrapper<Comments> generateQueryByAdminId(QueryByAdminIdDto query) {

        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda();

        if (StringUtils.isNotEmpty(query.getAdminId())) {
            queryWrapper.eq(Comments::getAdminId, query.getAdminId());
        }

        if (StringUtils.isNotBlank(query.getServeStartTime()) || StringUtils.isNotBlank(query.getServeEndTime())) {
            String timeStart = query.getServeStartTime();
            String timeEnd = query.getServeEndTime();

            if(StringUtils.isBlank(timeStart)){
                timeStart = "1991-03-29 00:00";
            }
            if(StringUtils.isBlank(timeEnd)){
                timeEnd = "2100-01-01 00:00";
            }

            queryWrapper.between(Comments::getCreatedTime, DateTimeUtils.yyyy_MM_dd_H_m(timeStart), DateTimeUtils.yyyy_MM_dd_H_m(timeEnd));
        }

        if (query.getCommentStar()>0) {
//            queryWrapper.eq(Comments::getCommentStar, query.getCommentStar());
            queryWrapper.le(Comments::getCommentStar, CommentStar.getEnum(query.getCommentStar()));
        }



        if (StringUtils.isNotBlank(query.getStoreId())) {
            queryWrapper.eq(Comments::getStoreId, query.getStoreId());
        }

        queryWrapper.eq(Comments::getShownToAdmin,true);
        queryWrapper.orderByDesc(Comments::getCreatedTime);

        return queryWrapper;
    }



    /**
     * 根据评论id，查询评论详情
     * @param id
     * @return
     */
    public QueryByAdminIdResponseDto queryCommetById(String id) {
        Comments comments = getCommentsById(id);
        QueryByAdminIdResponseDto commentsResponseDto = queryCovertToDto(comments);
        return commentsResponseDto;
    }



    /**
     * 根据店铺id 查询评论列表
     * @param queryByStoredDto
     * @return
     */
    public PageResponseDTO<QueryByAdminIdResponseDto> selectListStoreIdPage(QueryByStoredDto queryByStoredDto) {
        //构造查询参数
        LambdaQueryWrapper<Comments> queryWrapper = generateQueryByStoreId(queryByStoredDto);

        IPage<Comments> orderIPage = commentsMapper.selectPage(queryByStoredDto.getPageObject(), queryWrapper);

        List<QueryByAdminIdResponseDto> collect = orderIPage.getRecords().stream()
                .map(this::queryCovertToDto)
                .collect(Collectors.toList());
        PageResponseDTO<QueryByAdminIdResponseDto> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }


    /**
     * 店铺评价查询
     * @param query
     * @return
     */
    private LambdaQueryWrapper<Comments> generateQueryByStoreId(QueryByStoredDto query) {

        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda();

        if (StringUtils.isNotBlank(query.getAdminId())) {
            queryWrapper.eq(Comments::getAdminId, query.getAdminId());
        }

        if (StringUtils.isNotBlank(query.getServeStartTime()) || StringUtils.isNotBlank(query.getServeEndTime())) {
            String timeStart = query.getServeStartTime();
            String timeEnd = query.getServeEndTime();

            if(StringUtils.isBlank(timeStart)){
                timeStart = "1991-03-29 00:00";
            }
            if(StringUtils.isBlank(timeEnd)){
                timeEnd = "2100-01-01 00:00";
            }

            queryWrapper.between(Comments::getCreatedTime, DateTimeUtils.yyyy_MM_dd_H_m(timeStart), DateTimeUtils.yyyy_MM_dd_H_m(timeEnd));
        }

        if (query.getCommentStar()>0) {
            queryWrapper.eq(Comments::getCommentStar, CommentStar.getEnum(query.getCommentStar()));
//            queryWrapper.lt(Comments::getCommentStar, query.getCommentStar());
        }



        if (StringUtils.isNotBlank(query.getStoreId())) {
            queryWrapper.eq(Comments::getStoreId, query.getStoreId());
        }
        queryWrapper.eq(Comments::getShownToAdmin,true);
//        queryWrapper.eq(Comments::getShownToUser,true);
        queryWrapper.orderByDesc(Comments::getCreatedTime);

        return queryWrapper;
    }



    /**
     * 个人中心-历史评价
     * @param queryByUserIdDto
     * @return
     */
    public PageResponseDTO<QueryByUserIdResponseDto> selectListUserIdPage(QueryByUserIdDto queryByUserIdDto) {
        //构造查询参数
        LambdaQueryWrapper<Comments> queryWrapper = generateQueryByUserId(queryByUserIdDto);
        List<Comments> records = commentsMapper.selectList(queryWrapper);
//        IPage<Comments> orderIPage = commentsMapper.selectPage(queryByUserIdDto.getPageObject(), queryWrapper);
//        List<Comments> records = orderIPage.getRecords();
        if(records!=null && records.size()>0){
            Long[] ids = records.stream().map(Comments::getId).toArray(Long[]::new);
            LambdaQueryWrapper<Comments> queryWrappers = new QueryWrapper<Comments>().lambda().in(Comments::getId,ids).orderByDesc(Comments::getCreatedTime);;
            records= commentsMapper.selectList(queryWrappers);
        }

        List<QueryByUserIdResponseDto> collect = records.stream()
                .map((Comments comments)->queryUserCovertToDto(comments,queryByUserIdDto))
                .collect(Collectors.toList());
        PageResponseDTO<QueryByUserIdResponseDto> dtos = new PageResponseDTO<>(queryByUserIdDto.getPageObject(), collect);
        return dtos;
    }


    /**
     * 处理返回数据
     * @param comments
     * @return
     */
    public QueryByUserIdResponseDto queryUserCovertToDto(Comments comments,QueryByUserIdDto queryByUserIdDto) {
        if(comments==null){
            return null;
        }
        supplementOrder(comments);
        QueryByUserIdResponseDto commentsResponseDto = new QueryByUserIdResponseDto();
        BeanUtils.copyProperties(comments, commentsResponseDto);
        String pics = comments.getPicIds();
        commentsResponseDto.covert(dispics(pics));
        //  根据用户id查询用户头像
//        commentsResponseDto.setUserImg(getUserImg(comments.getUserId()));
        try {
            String userId = comments.getUserId();
            Map<String,String> map =  adminRemoteService.queryUserInfo(userId);
            commentsResponseDto.setUserImg(map.get("f_avatar"));
            commentsResponseDto.setUserNickName(map.get("f_name"));
        }catch (Exception e){

        }

        if(commentsResponseDto.getAnonymous() && !"1".equals(queryByUserIdDto.getIsUser())){
            commentsResponseDto.setUserNickName("匿名星粉");
        }
        return commentsResponseDto;
    }

    /**
     * 处理图片信息
     * @param pics
     * @return
     */
    public String  dispics(String pics){
        if(StringUtils.isNotEmpty(pics)){
            pics= Arrays.asList( pics.split(",")).stream().map(s-> Constant.OSS_ADDS+s).collect(Collectors.joining(","));
        }
        return pics;
    }

    /**
     * 个人评价查询
     * @param query
     * @return
     */
    private LambdaQueryWrapper<Comments> generateQueryByUserId(QueryByUserIdDto query) {

        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().select("id").lambda();
        String[] strings = adminRemoteService.queryUserIds(query.getUserId());
        if ("1".equals(query.getIsUser())) {
            //代码优化 获取账号合并ids

            queryWrapper.in(Comments::getUserId, strings);
//            queryWrapper.eq(Comments::getUserId, query.getUserId());
        }else if("0".equals(query.getIsUser())){
            queryWrapper.eq(Comments::getStoreId, String.valueOf(query.getStoreId()));
            queryWrapper.in(Comments::getCommentStar, new CommentStar[]{CommentStar.FOUR, CommentStar.FIVE});
        }else {
            queryWrapper.in(Comments::getUserId, strings);
        }
        queryWrapper.eq(Comments::getIsEffective,true);
        if (StringUtils.isNotEmpty(query.getLabels())){
            String[] split = query.getLabels().split(",");
            LambdaQueryWrapper<Comments> lambda = new QueryWrapper<Comments>().lambda();
            for (String s : split) {
                lambda.or().apply(" FIND_IN_SET("+s.trim()+", labels)");
            }
            queryWrapper.nested(i -> lambda);
        }
        queryWrapper.eq(Comments::getShownToUser,true);
        queryWrapper.orderByDesc(Comments::getCreatedTime);
        int i = (query.getPageNo() - 1) * query.getPageSize();
        queryWrapper.last("LIMIT "+i+","+query.getPageSize());
        return queryWrapper;
    }



    /**
     * 根据评论id，查询评论详情
     * @param id
     * @return
     */
    public QueryUserCenterResponseDto queryCommetCenter(String id) {
        Comments comments = getCommentsById(id);
        QueryUserCenterResponseDto commentsResponseDto = queryCenterCovertToDto(comments);
        return commentsResponseDto;
    }



    /**
     * 处理返回数据
     * @param comments
     * @return
     */
    public QueryUserCenterResponseDto queryCenterCovertToDto(Comments comments) {
        if(comments==null){
            return null;
        }
        QueryUserCenterResponseDto commentsResponseDto = new QueryUserCenterResponseDto();
        BeanUtils.copyProperties(comments, commentsResponseDto);
        List<Labels> labels =  queryLabelsByStart(comments.getCommentStar().getKey());
        List<LabelsResponseDto> labelsList = labels.stream()
                .map(this::labelsCovertToDto)
                .collect(Collectors.toList());
        commentsResponseDto.covert(comments,labelsList,adminRemoteService.getAdminImg(comments.getAdminId()));
        return commentsResponseDto;
    }


    /**
     * 处理匿名信息
     * @param commentsResponseDto
     */
    public void  disposeNick(QueryByAdminIdResponseDto commentsResponseDto,Comments comments){
        //判断是否是匿名用户
        if(commentsResponseDto.getAnonymous()){
            commentsResponseDto.setUserNickName("匿名星粉");
        }else{
            //  根据用户id查询用户头像和昵称
            Map<String, String> map = adminRemoteService.queryUserInfo(comments.getUserId());
            if(!map.isEmpty()){
                commentsResponseDto.setUserImg(map.get("f_avatar"));
                commentsResponseDto.setUserNickName(map.get("f_name"));

            }
        }
    }



    /**
     * 添加评论 根据订单id
     * @param
     * @return
     */
    public long insertComment(CommentInitDto commentInitDto) {
        commentInitDto.covert(commentInitDto.getCommentNotFilter());
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentInitDto, comments);
        ResponseUtils<OrderDetailResponseDto> responseUtils =  orderFeignService.queryOrder(commentInitDto.getOrderId(),true);
        if(!responseUtils.success()){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单不存在");
        }
        BeanUtils.copyProperties(responseUtils.getData(), comments);
        if(responseUtils.getData()!=null){
            OrderDetailResponseDto data = responseUtils.getData();
            comments.setOrderId(String.valueOf(data.getId()));

        }
        commentsMapper.insert(comments);
        return comments.getId();
    }

    /**
     * 添加评论 根据订单No
     * @param
     * @return
     */
    public long insertCommentNo(CommentNoInitDto commentNoInitDto) {
        commentNoInitDto.covert(commentNoInitDto.getCommentNotFilter());
        Comments comments = new Comments();
        BeanUtils.copyProperties(commentNoInitDto, comments);
        ResponseUtils<OrderDetailResponseDto> responseUtils =  orderFeignService.queryOrderNo(commentNoInitDto.getOrderNo(),false);
        if(!responseUtils.success()){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单不存在");
        }
        BeanUtils.copyProperties(responseUtils.getData(), comments);
        comments.setOrderId(String.valueOf(responseUtils.getData().getId()));
        comments.setShownToUser(true);
        comments.setShownToAdmin(true);
        commentsMapper.insert(comments);
        orderFeignService.comment(commentNoInitDto.getOrderNo());
        return comments.getId();
    }


    /**
     * 根据订单id 查询订单的评论
     * @param orderId
     * @return
     */
    public Comments queryDetailByorderId(String orderId) {
        Comments comments = commentsMapper.selectOne(new QueryWrapper<Comments>().lambda().eq(Comments::getOrderId, orderId).last("LIMIT 1"));
        if (comments == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单评论不存在");
        }
        supplementOrder(comments);
        comments.setPicIds( dispics(comments.getPicIds()));
        return comments;
    }


    /**
     * 根据订单no 查询订单的评论
     * @param orderNo
     * @return
     */
    public Comments queryDetailByorderNo(String orderNo) {
        Comments comments = commentsMapper.selectOne(new QueryWrapper<Comments>().lambda().eq(Comments::getOrderNo, orderNo).last("LIMIT 1"));
        if (comments != null) {
            supplementOrder(comments);
        }
        return comments;
    }


    /**
     *  查询标签数据
     * @param start
     * @return
     */
    public List<Labels> queryLabelsByStart(int start) {
        List<Labels> labels =  labelsMapper.selectList(generateQueryByStart(start));
        log.info("queryLabelsByStart{}",JSON.toJSONString(labels));
        if (labels == null) {
            throw new BusinessException(BusinessException.Type.DEFAULT, "该标签不存在");
        }
        return labels;
    }


    private LambdaQueryWrapper<Labels> generateQueryByStart(int start) {
        LambdaQueryWrapper<Labels> queryWrapper = new QueryWrapper<Labels>().lambda();
        if(start>0){
            queryWrapper.eq(Labels::getStartNum, start);
        }
        queryWrapper.notIn(Labels::getStartNum,0);
        queryWrapper.orderByAsc(Labels::getCreatedTime);
        return queryWrapper;
    }


    public LabelsResponseDto labelsCovertToDto(Labels labels) {
        if(labels==null){
            return null;
        }
        LabelsResponseDto labelsResponseDto = new LabelsResponseDto();
        BeanUtils.copyProperties(labels, labelsResponseDto);
        return labelsResponseDto;
    }


    /**
     * 根据用户id查询用户头像
     * @param id
     * @return
     */
    public String getUserImg(String id){
        Map<String, String> map = adminRemoteService.queryUserInfo(id );
        return map.get("f_avatar");
    }


    /**
     * 远程调用comments中最新信息
     * 店铺信息
     * 发型师名称
     * @param comments
     */
    public void supplementOrder(Comments comments){
        log.info("supplementOrder 远程调用comments中最新信息:{}", comments);
        //查询店铺最新信息
        StoreRemoteDto storeRemoteDto = storeRemoteService.getByStoreId(comments.getStoreId());
        log.info("supplementOrder 远程调用店铺最新信息:{}", storeRemoteDto);
        if(storeRemoteDto!=null){
            BeanUtils.copyProperties(storeRemoteDto, comments);
        }
        //查询发型师名称
        comments.setAdminName(adminRemoteService.getAdminName(comments.getAdminId()));
    }


    /**
     * 根据店铺id获取该门店查询好评数
     * @param storeId
     * @return
     */
    @Cacheable(value = "cache:comments:getReviews", key = "#storeId")
    public Integer getReviews(String storeId){
        log.info("取该门店查询好评数:{}", storeId);
        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda();
        queryWrapper.eq(Comments::getStoreId, storeId);
        queryWrapper.eq(Comments::getIsEffective,true);
        queryWrapper.eq(Comments::getShownToUser,true);
        queryWrapper.eq(Comments::getShownToAdmin,true);
        queryWrapper.in(Comments::getCommentStar, new CommentStar[]{CommentStar.FOUR, CommentStar.FIVE});
        Integer integer = commentsMapper.selectCount(queryWrapper);
        return integer;
    }

    /**
     *  查询好评
     * @param storeId
     * @return
     */
    @Cacheable(value = "cache:comments:getReviewComments", key = "#storeId")
    public Comments getReviewComments(String storeId){
        log.info("获取门店一条好评:{}", storeId);
        Comments comments = queryReviewComments(storeId, "1");
        if(comments==null){
            comments =  queryReviewComments(storeId,"0");
        }else {
            comments.setPicIds( dispics(comments.getPicIds()));
        }
        if(comments!=null){
            supplementOrder(comments);
        }
        return comments;
    }


    /**
     * 最新带图好评的评论信息
     * @param storeId
     * @param parameter   1：带图，0：不带图
     * @return
     */
    public Comments queryReviewComments(String storeId,String parameter){
        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda();
        queryWrapper.eq(Comments::getStoreId, storeId);
        if("1".equals(parameter)){
            queryWrapper.isNotNull(Comments::getPicIds);
        }
        queryWrapper.eq(Comments::getIsEffective,true);
        queryWrapper.eq(Comments::getShownToUser,true);
        queryWrapper.eq(Comments::getShownToAdmin,true);

        queryWrapper.in(Comments::getCommentStar, new CommentStar[]{CommentStar.FOUR, CommentStar.FIVE});
        queryWrapper.orderByDesc(Comments::getCreatedTime).last("LIMIT 1");
        Comments comments= commentsMapper.selectOne(queryWrapper);
        return comments;
    }

    /**
     * 下单屏评论显示
     * @param storeId
     * @return
     */
    public List<ScreenCommentDto> praise(String storeId) {
        Set<Long> adminIds = wordPadRemoteService.getAdminIds(storeId);
        log.info("adminIds:{}", adminIds);
        List<Comments> comments = new ArrayList<>();
        adminIds.forEach(Long -> comments.addAll(queryComments(Long,"1",5)));
        int total = adminIds.size()*5;
        if(total==0){
            total=5;
        }
        int num = comments.size();
        if(total>num){
            int surplus = total-num;
            comments.addAll(queryComments(null,"0",surplus));
        }
        List<Comments> comms = new ArrayList<>();
        if(comments!=null && comments.size()>0){
            Long[] ids = comments.stream().map(Comments::getId).toArray(Long[]::new);
            LambdaQueryWrapper<Comments> queryWrappers = new QueryWrapper<Comments>().lambda().in(Comments::getId,ids).orderByDesc(Comments::getCreatedTime);;
            comms.addAll(commentsMapper.selectList(queryWrappers));
        }

        List<ScreenCommentDto> collect = comms.parallelStream()
                .map(this::queryScreen)
                .collect(Collectors.toList());
        return collect;
    }


    public ScreenCommentDto queryScreen(Comments comments){
        ScreenCommentDto screenCommentDto = new ScreenCommentDto();
        BeanUtils.copyProperties(comments, screenCommentDto);
        screenCommentDto.conve(adminRemoteService.getAdminName(comments.getAdminId()),adminRemoteService.queryUserInfo(String.valueOf(comments.getUserId())));
        return screenCommentDto;
    }


    public List<Comments> queryComments(Long adminId,String type,int num){
        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().select("id").lambda();
        if("1".equals(type)){
            queryWrapper.eq(Comments::getAdminId, String.valueOf(adminId));
        }
        queryWrapper.eq(Comments::getCommentStar, CommentStar.FIVE);
        queryWrapper.eq(Comments::getIsEffective, true);
        queryWrapper.eq(Comments::getShownToUser, true);
        queryWrapper.isNotNull(Comments::getComment);
        queryWrapper.orderByDesc(Comments::getCreatedTime);
        queryWrapper.last("LIMIT "+num);
        List<Comments> comments = commentsMapper.selectList(queryWrapper);
        log.info("get comments:{}", JSON.toJSONString(comments));
        return comments;
    }


    /**
     * 查询店铺当日有效差评
     * @param storeId
     * @return
     */
    public String querybadComment(String storeId){
        Integer integer = commentsMapper.selectCount(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true).eq(Comments::getShownToAdmin,true).eq(Comments::getStoreId,storeId).in(Comments::getCommentStar, new CommentStar[]{CommentStar.ONE,CommentStar.TWO,CommentStar.THREE}).apply(" date(created_time) = curdate()"));
        if(integer>0){
            return "今日"+integer+"差评";
        }
        return "";
    }


    /**
     * 评价记录
     * @param queryByUserIdDto
     * @return
     */
    public PageResponseDTO<QueryCommetsDto> queryCommentsByUserId(QueryByUserIdDto queryByUserIdDto) {
        //构造查询参数
        LambdaQueryWrapper<Comments> queryWrapper = queryCommentsByUserIdDao(queryByUserIdDto);
        IPage<Comments> orderIPage = commentsMapper.selectPage(queryByUserIdDto.getPageObject(), queryWrapper);

        List<QueryCommetsDto> collect = orderIPage.getRecords().stream()
                .map(this::queryCommentsCovertToDto)
                .collect(Collectors.toList());
        PageResponseDTO<QueryCommetsDto> dtos = new PageResponseDTO<>(orderIPage, collect);
        return dtos;
    }


    /**
     * 评价记录查询
     * @param
     * @return
     */
    private LambdaQueryWrapper<Comments> queryCommentsByUserIdDao(QueryByUserIdDto query) {
        LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda();
        String[] strings = adminRemoteService.queryUserIds(query.getUserId());
        queryWrapper.in(Comments::getUserId, strings);
        queryWrapper.orderByDesc(Comments::getCreatedTime);
        return queryWrapper;
    }

    /**
     * 评价记录处理返回数据
     * @param comments
     * @return
     */
    public QueryCommetsDto queryCommentsCovertToDto(Comments comments) {
        if(comments==null){
            return null;
        }
        supplementOrder(comments);
        comments.setPicIds( dispics(comments.getPicIds()));
        QueryCommetsDto commentsResponseDto = new QueryCommetsDto();
        BeanUtils.copyProperties(comments, commentsResponseDto);
        commentsResponseDto.covert(comments);
        return commentsResponseDto;
    }

    /**
     * 查询门店当日评论与差评数
     * @param
     * @return
     */
    public Map<String,Integer> queryServiceQuailty(String storeId, LocalDateTime startTime, LocalDateTime endTime) {
        Integer integer = commentsMapper.selectCount(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true).eq(Comments::getStoreId, storeId)
                .between(Comments::getCreatedTime, startTime, endTime));

        Integer integer1 = commentsMapper.selectCount(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true).eq(Comments::getStoreId, storeId)
                .between(Comments::getCreatedTime, startTime, endTime)
                .in(Comments::getCommentStar, new CommentStar[]{CommentStar.ONE, CommentStar.TWO, CommentStar.THREE}));
        log.info("共查询到{}条评论",integer);
        log.info("其中有{}条差评",integer1);
        Map<String,Integer> map = new HashMap<>();
        map.put("dayComments",integer);
        map.put("dayNegativeComments",integer1);
        return map;
    }

    /**
     * @description: 获取当天开始时间
     * @author: ch
     * @Param [date, hour, minute, second]
     * @return java.time.LocalDateTime
     * @date: 2019-07-16 18:02
     **/
    public static LocalDateTime  timeTransition(String date){
        LocalDate localDate = DateTimeUtils.yyyy_MM_dd(date);
        LocalDateTime of = LocalDateTime.of(localDate, LocalTime.now()).withHour(0).withMinute(0).withSecond(0).withNano(0);
        return of;
    }

    /**
     * 服务质量详情
     * @param storeId
     * @param startTime
     * @param endTime
     * @return
     */
    public Set<String> queryDetailServiceQuality(String storeId, LocalDateTime startTime,LocalDateTime endTime) {
        List<Comments> commentsList = commentsMapper.selectList(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true)
                .eq(Comments::getStoreId, storeId)
                .between(Comments::getCreatedTime, startTime, endTime)
                .groupBy(Comments::getAdminId));
        Set<String> hashSet = new HashSet<>();
        if (commentsList.size()!=0) {
            for (int i = 0, length = commentsList.size(); i < length; i++) {
                hashSet.add(commentsList.get(i).getAdminId());
            }
        }
        return hashSet;
    }

    /**
     * 发型师评论与差评数
     * @param storeId
     * @param adminId
     * @param startTime
     * @param endTime
     * @return
     */
    public Map<String,Integer> serviceAdminId(String storeId,String adminId, LocalDateTime startTime,LocalDateTime endTime) {
        Map<String,Integer> hashMap = new HashMap<>();
        Integer integer = commentsMapper.selectCount(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true)
                .eq(Comments::getAdminId, adminId)
                .eq(Comments::getStoreId, storeId)
                .between(Comments::getCreatedTime, startTime, endTime));
        Integer integer1 = commentsMapper.selectCount(new QueryWrapper<Comments>().lambda().eq(Comments::getIsEffective, true)
                .eq(Comments::getAdminId, adminId)
                .eq(Comments::getStoreId,storeId)
                .between(Comments::getCreatedTime, startTime, endTime)
                .in(Comments::getCommentStar, new CommentStar[]{CommentStar.ONE, CommentStar.TWO, CommentStar.THREE}));
        hashMap.put("dayCommentsList",integer);
        hashMap.put("dayNegativeCommentsList",integer1);
        return hashMap;
    }




    /**
     * @description: 获取订单号
     * @author: ch
     * @Param [orders]
     * @return java.lang.String[]
     * @date: 2019-08-06 16:49
     **/
    public List<Object>  queryorserNos(List<Comments> comments) {
        if (comments.isEmpty()) {
            return new ArrayList<>();
        }
        String[] orderNos = comments.stream().map(Comments::getOrderNo).toArray(String[]::new);
        ResponseUtils<List<Object>> listResponseUtils = orderFeignService.cutomerList(orderNos);
        if(listResponseUtils.success()){
            return listResponseUtils.getData();
        }
        return new ArrayList<>();
    }

    
    /**
    * @description: 修改售后状态
    * @author: ch
    * @Param [orderNo]
    * @return boolean
    * @date: 2019-08-06 18:52
    **/
    public boolean edithadComment(String orderNo) {
        Comments comments = commentsMapper.selectOne(new QueryWrapper<Comments>().lambda().eq(Comments::getOrderNo, orderNo).last("LIMIT 1"));
        comments.setAftermarketStatus(true);
        commentsMapper.updateById(comments);
        return true;
    }

    /**
     * 服务发型师name
     * @author: lyz
     * @param storeId
     * @return
     */
    public List<Map<String, Object>>  serviceAdmin(String storeId) {
        List<Map<String, Object>> collect = null;
        try {
            if (null != storeId && storeId.length() != 0){
                LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda().eq(Comments::getStoreId, storeId)
                        .select(Comments::getAdminId, Comments::getAdminName)
                        .groupBy(Comments::getAdminId);
                collect = commentsMapper.selectMaps(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("completeSuccessMessage error:{}",e);
        }
        return collect;
    }

    /**
     * 店铺name
     * @author: lyz
     * @param adminId
     * @return
     */
    public List<Map<String, Object>>  serviceStore(String adminId) {
        List<Map<String, Object>> collect = null;
        try {
            if (null != adminId && adminId.length()!=0) {
                LambdaQueryWrapper<Comments> queryWrapper = new QueryWrapper<Comments>().lambda().eq(Comments::getAdminId, adminId)
                        .select(Comments::getStoreId, Comments::getStoreName)
                        .groupBy(Comments::getStoreId);
                collect = commentsMapper.selectMaps(queryWrapper).stream().filter(Objects::nonNull).collect(Collectors.toList());
            }
        } catch (Exception e) {
            log.error("completeSuccessMessage error:{}",e);
        }
        return collect;
    }
}
